package vn.edu.uit.game_show;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import vn.edu.uit.game_show.utilities.Contents;
import vn.edu.uit.game_show.utilities.QRCodeEncoder;
import vn.edu.uit.game_show.utilities.WebserviceHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;

public class DangNhap extends Activity{
	
	EditText etHoten;
	EditText etMSGV;
	Button btnDangNhap;

	String tenNhom = "";
	String msgv = "";

	ProgressBar prKhoiTao;
	public static String ipAddress = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_dang_nhap);
		
		SharedPreferences prefs = getSharedPreferences("TaiKhoanNhom", 0);
		tenNhom = prefs.getString("tenNhom", "");

		etHoten = (EditText) findViewById(R.id.etHoTen);
		etHoten.setHint(Html.fromHtml("<i>Đặt tên nhóm</i>"));
		etHoten.setText(tenNhom);

		btnDangNhap = (Button) findViewById(R.id.btnLogin);
		btnDangNhap.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				tenNhom = etHoten.getText().toString().trim();

				SharedPreferences prefs = getSharedPreferences("TaiKhoanNhom", 0);
				SharedPreferences.Editor editor = prefs.edit();
				editor.putString("tenNhom", tenNhom);
				editor.commit();
				new ScanIPAsyncTask(prKhoiTao).execute();
			}
		});
		
		prKhoiTao = (ProgressBar) findViewById(R.id.progKhoiTao);
	}
	
	public void switchView() {
		Intent intent = new Intent(getApplicationContext(),	ThietLap.class);
		startActivity(intent);
		finish();
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}
	
	final class ScanIPAsyncTask extends AsyncTask<Void, Void, Void> {

		private Boolean isSuccess = false;
		private ProgressBar pR;

		public ScanIPAsyncTask(ProgressBar progress) {
			pR = progress;
			pR.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onPreExecute() {
			pR.setVisibility(View.VISIBLE);

		}

		@Override
		protected Void doInBackground(final Void... params) {
			/* Load timezone. this is very slow - may take up to 3 seconds. */
			if (WebserviceHelper.getInstance() != null) {
				WebserviceHelper.destroyInstance();
			}
			isSuccess = WebserviceHelper.isNetAvailable(DangNhap.this);
			if (isSuccess) {
				
				ipAddress = WebserviceHelper.getIPAddress();
				SharedPreferences prefs = getSharedPreferences("TaiKhoanNhom", 0);
				SharedPreferences.Editor editor = prefs.edit();
				editor.putString("ip", ipAddress.trim());
				editor.putString("port", "54321");
				editor.commit();

				try {
					createQRCode(ipAddress.trim(), "54321");					
				} catch (WriterException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} 
			
			return null;
			
		}

		@Override
		protected void onPostExecute(final Void unused) {
			pR.setVisibility(View.INVISIBLE);
			if (isSuccess) {	
				switchView();
			} else {
				showDialog(0);
			}
		}
	}

	public void createQRCode(String ip, String port) throws WriterException,
			IOException {

		String input = "2#"+tenNhom+"#"+ ip + "#" + port;
		int smallerDimension = 300;

		QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(input.trim(), null,
				Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(),
				smallerDimension);
		Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();

		String filename = "/game/qrcode.png";
		File sd = Environment.getExternalStorageDirectory();
		File dest = new File(sd, filename);

		FileOutputStream out = new FileOutputStream(dest);
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
		out.flush();
		out.close();
	}

	public Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Lỗi xảy ra").setMessage("Không có kết nối mạng!")
				.setPositiveButton("Thoát", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						finish();
					}
				});
		return builder.create();
	}
	
}
